package com.freesky.biz.icbc.service.impl;

import com.freesky.biz.icbc.domain.TAigouActivity;
import com.freesky.biz.icbc.domain.TAigouCategory;
import com.freesky.biz.icbc.domain.TreeCategorySelect;
import com.freesky.biz.icbc.mapper.AigouActivityMapper;
import com.freesky.biz.icbc.mapper.AigouCategoryMapper;
import com.freesky.biz.icbc.service.IAigouActivityService;
import com.freesky.biz.icbc.service.IAigouCategoryService;
import com.freesky.common.constant.UserConstants;
import com.freesky.common.core.domain.TreeSelect;
import com.freesky.common.core.domain.entity.SysDept;
import com.freesky.common.core.text.Convert;
import com.freesky.common.exception.ServiceException;
import com.freesky.common.utils.StringUtils;
import com.freesky.common.utils.spring.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AigouCategoryServiceImpl implements IAigouCategoryService {

    private static final Logger logger = LoggerFactory.getLogger(AigouCategoryServiceImpl.class);

    @Autowired
    private AigouCategoryMapper aigouCategoryMapper;


    @Override
    public List<TAigouCategory> selectCategoryList(TAigouCategory entity) {
        return aigouCategoryMapper.selectCategoryList(entity);
    }

    @Override
    public List<TreeCategorySelect> selectDeptTreeList(TAigouCategory entity) {
        List<TAigouCategory> depts = SpringUtils.getAopProxy(this).selectCategoryList(entity);
        return buildCategoryTreeSelect(depts);
    }

    @Override
    public List<TAigouCategory> buildCategoryTree(List<TAigouCategory> entitys) {
        List<TAigouCategory> returnList = new ArrayList<TAigouCategory>();
        List<String> tempList = entitys.stream().map(TAigouCategory::getCategoryId).collect(Collectors.toList());
        for (TAigouCategory aigouCategory : entitys)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(aigouCategory.getParentId()))
            {
                recursionFn(entitys, aigouCategory);
                returnList.add(aigouCategory);
            }
        }
        if (returnList.isEmpty()) {
            returnList = entitys;
        }
        return returnList;
    }

    @Override
    public List<TreeCategorySelect> buildCategoryTreeSelect(List<TAigouCategory> entitys) {
        List<TAigouCategory> deptTrees = buildCategoryTree(entitys);
        return deptTrees.stream().map(TreeCategorySelect::new).collect(Collectors.toList());
    }

    @Override
    public TAigouCategory selectCategoryById(String categoryId) {
        return aigouCategoryMapper.selectCategoryById(categoryId);
    }

    @Override
    public List<TAigouCategory> selectChildrenCategoryById(String categoryId) {
        return aigouCategoryMapper.selectChildrenCategoryById(categoryId);
    }

    @Override
    public int selectNormalChildrenCategoryById(String categoryId) {
        return aigouCategoryMapper.selectNormalChildrenCategoryById(categoryId);
    }

    @Override
    public boolean hasChildByCategoryId(String categoryId) {
        int result = aigouCategoryMapper.hasChildByCategoryId(categoryId);
        return result > 0;
    }

    @Override
    public int insertCategory(TAigouCategory entity) {
        TAigouCategory info = aigouCategoryMapper.selectCategoryById(entity.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (info!=null && !UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new ServiceException("类别停用，不允许新增");
        }
        if(info!=null) {
            entity.setAncestors(info.getAncestors() + "," + entity.getParentId());
        } else {
            entity.setAncestors(entity.getParentId());
        }

        return aigouCategoryMapper.insertCategory(entity);
    }

    @Override
    public int updateCategory(TAigouCategory entity) {
        TAigouCategory newParentDept = aigouCategoryMapper.selectCategoryById(entity.getParentId());
        TAigouCategory oldDept = aigouCategoryMapper.selectCategoryById(entity.getCategoryId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getCategoryId();
            String oldAncestors = oldDept.getAncestors();
            entity.setAncestors(newAncestors);
            updateCategoryChildren(entity.getCategoryId(), newAncestors, oldAncestors);
        }
        int result = aigouCategoryMapper.updateCategory(entity);
        if (UserConstants.DEPT_NORMAL.equals(entity.getStatus()) && StringUtils.isNotEmpty(entity.getAncestors())
                && !StringUtils.equals("0", entity.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateCategoryStatusNormal(entity);
        }
        return result;
    }


    private void updateCategoryStatusNormal(TAigouCategory entity)
    {
        String ancestors = entity.getAncestors();
        String[] deptIds = Convert.toStrArray(ancestors);
        aigouCategoryMapper.updateCategoryStatusNormal(deptIds);
    }

    public void updateCategoryChildren(String categoryId, String newAncestors, String oldAncestors)
    {
        List<TAigouCategory> children = aigouCategoryMapper.selectChildrenCategoryById(categoryId);
        for (TAigouCategory child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            aigouCategoryMapper.updateCategoryChildren(children);
        }
    }

    @Override
    public int deleteCategoryById(String categoryId) {
        return aigouCategoryMapper.deleteCategoryById(categoryId);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<TAigouCategory> list, TAigouCategory t)
    {
        // 得到子节点列表
        List<TAigouCategory> childList = getChildList(list, t);
        t.setChildren(childList);
        for (TAigouCategory tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<TAigouCategory> getChildList(List<TAigouCategory> list, TAigouCategory t)
    {
        List<TAigouCategory> tlist = new ArrayList<TAigouCategory>();
        Iterator<TAigouCategory> it = list.iterator();
        while (it.hasNext())
        {
            TAigouCategory n = (TAigouCategory) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().equals(t.getCategoryId()))
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<TAigouCategory> list, TAigouCategory t)
    {
        return getChildList(list, t).size() > 0;
    }
}
